package com.cms.controller.front;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.cms.Feedback;
import com.cms.entity.Member;
import com.cms.routes.RouteMapping;
import com.cms.util.SystemUtils;
import com.haierubic.bigdata.commons.util.HttpClientUtils;

/**
 * Controller - 登录
 * 
 * 
 * 
 */
@RouteMapping(url = "/login")
public class LoginController extends BaseController {

	/**
	 * 登录页面
	 */
	public void index() {
		String username = getPara("username");
		String password = getPara("password");
		if (StringUtils.isNotBlank(username)
				&& StringUtils.isNotBlank(password)) {
			Member member = new Member().dao().findByUsername(username);
			if (member == null) {
				setAttr("feedback", Feedback.error("用户不存在"));
			} else if (!DigestUtils.md5Hex(password).equals(
					member.getPassword())) {
				setAttr("feedback", Feedback.error("用户名密码错误"));
			} else {
				getSession().setAttribute(Member.SESSION_MEMBER, member);
				redirect("/");
				return;
			}
		}
		render("/templates/" + getTheme() + "/" + getDevice() + "/login.html");
	}

	// WXLoginController.java:
	/**
	 * 微信公众号网页授权登录:
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ParseException
	 */
	public void wxLoginss() {
		// 第一步：用户同意授权，获取code
		// WXAuthUtil.APPID 微信公众号的appenid 这个是微信公众号后台获取的
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
				+ SystemUtils.getConfig().getWeixinpayAppId()
				+ "&redirect_uri="
				+ URLEncoder.encode("http://wap.12us.com/login/callBackss") // 这个是我们回调的地址
																			// 在这里进行出来获取到用户的心
				+ "&response_type=code"
				+ "&scope=snsapi_userinfo"
				+ "&state=123#wechat_redirect";

		System.out.println("--forward重定向地址-------:" + url);
		redirect(url);// 必须重定向，否则不能成功
	}

	/**
	 * 微信网页登录回调接口
	 * 
	 * @param wechatUser
	 * @param modelMap
	 * @param req
	 * @param resp
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public void callBackss() throws ServletException, IOException {
		// 如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE
		// https://xxxxx/xxxxx/callBackss.do?code=CODE&state=STATE
		// 获取code code作为换取access_token的票据
		String code = getPara("code");
		System.out.println("授权返回code信息---------:" + code);
		// 第二步：通过code换取网页授权access_token (获取openid接口)
		// WXAuthUtil.APPID 公众号的Appid
		// WXAuthUtil.APPSECRET 公众号的APPSECRET 可以在微信公众号后台获取
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
				+ SystemUtils.getConfig().getWeixinpayAppId() + "&secret="
				+ SystemUtils.getConfig().getWeixinpayKey() + "&code=" + code
				+ "&grant_type=authorization_code";

		// 发送请求 get提交 拿code凭证去获取openid和access_token
		JSONObject jsonObject = JSONObject.parseObject(HttpClientUtils
				.getForJson(url, new HashMap<String, String>()));

		String openid = jsonObject.getString("openid");
		String access_token = jsonObject.getString("access_token");
		String refresh_token = jsonObject.getString("refresh_token");

		// 拿到用户openid 和access_token 去获取用户信息
		// 第五步,验证access_token是否过期
		String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token="
				+ access_token + "&openid=" + openid;
		JSONObject chickuserInfo = JSONObject.parseObject(HttpClientUtils
				.getForJson(chickUrl, new HashMap<String, String>()));

		// 由于access_token拥有较短的有效期，当access_token超时后，可以使用refresh_token进行刷新，refresh_token有效期为30天，当refresh_token失效之后，需要用户重新授权
		// 如果发送错误，就有可能是access_token过期了 errcode 的值是 0
		// 那么就是没有问题，access_token没有过期,不等于0就是过期，那么我们要去刷新access_token
		if (!"0".equals(chickuserInfo.getString("errcode"))) {
			// 第三步刷新access_token(刷新access_token接口)
			String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
					+ openid
					+ "&grant_type=refresh_token&refresh_token="
					+ refresh_token;

			JSONObject refreshInfo = JSONObject.parseObject(HttpClientUtils
					.getForJson(refreshTokenUrl, new HashMap<String, String>()));

			access_token = refreshInfo.getString("access_token");
		}

		// 获取用户拿到openid 和access_token去获取用户信息，在页面中进行业务处理，获取存储在数据库中:
		// 第四步(获取用户接口)
		String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="
				+ access_token + "&openid=" + openid + "&lang=zh_CN";

		JSONObject userInfo = JSONObject.parseObject(HttpClientUtils
				.getForJson(infoUrl, new HashMap<String, String>() {
					{
						put("Content-type", "application/json;charset=utf-8");
					}
				}));

		System.out.println("userInfo------:" + userInfo.toString());
		userInfo.getString("nickname");
		userInfo.getString("sex");
		userInfo.getString("country");
		userInfo.getString("province");
		userInfo.getString("city");
		userInfo.getString("headimgurl");
		userInfo.getString("language");
		userInfo.getString("privilege");
		userInfo.getString("openid");
		userInfo.getString("unionid");
		setAttr("openId", userInfo.getString("openid"));
		// modelMap.put("nickname", userInfo.getString("nickname"));//保存授权用户
		setAttr("nickname", userInfo.getString("nickname"));
		// render("/templates/"+getTheme()+"/"+getDevice()+"/login2.html");

		if (userInfo == null || !userInfo.containsKey("openid")) {
			setAttr("feedback", Feedback.error("用户不存在"));
		} else {
			Member member=new Member().findByOpenId(userInfo.getString("openid"));
			if(null==member){
				member=new Member();
				member.setWeixinOpenId(userInfo.getString("openid"));
				member.setUsername(userInfo.getString("nickname"));
				member.setAddress(userInfo.getString("country")+"-"+userInfo.getString("province")+"-"+userInfo.getString("city"));
				member.registerMember(member);
				member=new Member().findByOpenId(userInfo.getString("openid"));
			}else{
				member.setUsername(userInfo.getString("nickname"));
				member.setAddress(userInfo.getString("country")+"-"+userInfo.getString("province")+"-"+userInfo.getString("city"));
				member=new Member().findByOpenId(userInfo.getString("openid"));
			}
			
			getSession().setAttribute(Member.SESSION_MEMBER, member);
			redirect("/");
			return;
		}
	}

}
